<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use app\service\LeaveApprovalService;

class ApprovalRecord extends BaseController
{
    /**
     * 提交审批申请
     */
    public function submit()
    {
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取请求参数
        $flowId = Request::param('flowId/d');
        $formData = Request::param('formData/a');
        $approverId = Request::param('approverId/d');

        // 参数验证
        if (empty($flowId) || empty($formData) || empty($approverId)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 检查审批流程是否存在且启用
        $flow = Db::name('approval_flow')
            ->where('id', $flowId)
            ->where('status', 1)
            ->find();
            
        if (!$flow) {
            return json(['code' => 400, 'msg' => '审批流程不存在或已停用']);
        }

        // 获取审批流程字段配置
        $flowFields = Db::name('approval_flow_field')
            ->where('flow_id', $flowId)
            ->order('sort asc')
            ->select()
            ->toArray();
            
        // 验证必填字段
        foreach ($flowFields as $field) {
            if ($field['is_required'] == 1) {
                $fieldId = $field['field_id'];
                if (!isset($formData[$fieldId]) || (is_string($formData[$fieldId]) && trim($formData[$fieldId]) === '')) {
                    return json(['code' => 400, 'msg' => $field['field_name'].'为必填项']);
                }
            }
        }

        // 检查审批人是否存在
        $approver = Db::name('user')
            ->where('id', $approverId)
            ->where('status', 1)
            ->find();
            
        if (!$approver) {
            return json(['code' => 400, 'msg' => '审批人不存在或已停用']);
        }

        // 插入审批记录
        try {
            $result = Db::name('approval_record')->insert([
                'flow_id' => $flowId,
                'user_id' => $user['id'],
                'form_data' => json_encode($formData, JSON_UNESCAPED_UNICODE),
                'status' => 1, // 1待审批
                'approver_id' => $approverId,
                'create_time' => date('Y-m-d H:i:s')
            ]);

            if ($result) {
                return json(['code' => 200, 'msg' => '提交成功']);
            } else {
                return json(['code' => 500, 'msg' => '提交失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 获取我的审批记录列表
     */
    public function getMyList()
    {
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取分页参数
        $page = Request::param('page/d', 1);
        $limit = Request::param('limit/d', 10);
        $status = Request::param('status/d'); // 可选的状态筛选

        // 构建查询
        $query = Db::name('approval_record')
            ->alias('r')
            ->join('approval_flow f', 'r.flow_id = f.id')
            ->join('user u', 'r.approver_id = u.id')
            ->where('r.user_id', $user['id']);

        // 如果指定了状态，添加状态筛选
        if (!is_null($status)) {
            $query = $query->where('r.status', $status);
        }

        // 获取总记录数
        $total = $query->count();

        // 获取分页数据
        $list = $query
            ->field([
                'r.id',
                'r.flow_id',
                'f.title as flow_title',
                'r.form_data',
                'r.status',
                'u.realname as approver_name',
                'r.approve_time',
                'r.approve_remark',
                'r.create_time'
            ])
            ->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'total' => $total,
                'list' => $list
            ]
        ]);
    }
    
    /**
     * 获取待我审批列表
     */
    public function getPendingList()
    {
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取分页参数
        $page = Request::param('page/d', 1);
        $limit = Request::param('limit/d', 10);
        $status = Request::param('status/d'); // 可选的状态筛选
        $keyword = Request::param('keyword/s', ''); // 关键字搜索
        $flowId = Request::param('flowId/d'); // 审批类型筛选
        $startDate = Request::param('startDate/s', ''); // 开始日期
        $endDate = Request::param('endDate/s', ''); // 结束日期

        // 构建查询
        $query = Db::name('approval_record')
            ->alias('r')
            ->join('approval_flow f', 'r.flow_id = f.id')
            ->join('user u', 'r.user_id = u.id')
            ->where('r.approver_id', $user['id']);

        // 如果指定了状态，添加状态筛选
        if (!is_null($status)) {
            $query = $query->where('r.status', $status);
        }
        
        // 关键字搜索（按申请人姓名）
        if (!empty($keyword)) {
            $query = $query->where('u.realname', 'like', "%{$keyword}%");
        }
        
        // 审批类型筛选
        if (!empty($flowId)) {
            $query = $query->where('r.flow_id', $flowId);
        }
        
        // 日期范围筛选
        if (!empty($startDate)) {
            $query = $query->where('r.create_time', '>=', $startDate . ' 00:00:00');
        }
        
        if (!empty($endDate)) {
            $query = $query->where('r.create_time', '<=', $endDate . ' 23:59:59');
        }

        // 获取总记录数
        $total = $query->count();

        // 获取分页数据
        $list = $query
            ->field([
                'r.id',
                'r.flow_id',
                'f.title as flow_title',
                'r.form_data',
                'r.status',
                'u.realname as applicant_name',
                'r.approve_time',
                'r.approve_remark',
                'r.create_time'
            ])
            ->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'total' => $total,
                'list' => $list
            ]
        ]);
    }
    
    /**
     * 处理审批
     */
    public function process()
    {
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取请求参数
        $id = Request::param('id/d');
        $action = Request::param('action/d'); // 2同意 3驳回
        $remark = Request::param('remark/s', '');

        // 参数验证
        if (empty($id) || !in_array($action, [2, 3])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 查询审批记录
        $record = Db::name('approval_record')
            ->where('id', $id)
            ->where('approver_id', $user['id'])
            ->where('status', 1) // 只能处理待审批的记录
            ->find();
            
        if (!$record) {
            return json(['code' => 400, 'msg' => '审批记录不存在或已处理']);
        }

        // 更新审批记录
        try {
            $result = Db::name('approval_record')
                ->where('id', $id)
                ->update([
                    'status' => $action,
                    'approve_time' => date('Y-m-d H:i:s'),
                    'approve_remark' => $remark
                ]);

            if ($result) {
                // 如果审批通过，检查是否为请假类型并同步请假记录
                if ($action == 2) {
                    // 添加调试日志
                    file_put_contents(__DIR__ . '/approval_debug_' . date('Y-m-d') . '.log', 
                        "[" . date('Y-m-d H:i:s') . "] 审批通过，开始调用LeaveApprovalService\n" . 
                        "传递的record数据: " . json_encode($record, JSON_UNESCAPED_UNICODE) . "\n", 
                        FILE_APPEND | LOCK_EX);
                    
                    $leaveService = new \app\service\LeaveApprovalService();
                    $result = $leaveService->handleApprovalPassed($record);
                    
                    file_put_contents(__DIR__ . '/approval_debug_' . date('Y-m-d') . '.log', 
                        "[" . date('Y-m-d H:i:s') . "] LeaveApprovalService调用结果: " . ($result ? '成功' : '失败') . "\n", 
                        FILE_APPEND | LOCK_EX);
                }
                
                return json(['code' => 200, 'msg' => '处理成功']);
            } else {
                return json(['code' => 500, 'msg' => '处理失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 撤销审批申请
     * 用户只能撤销自己提交的、且状态为待审批的申请
     */
    public function cancel()
    {
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取请求参数
        $id = Request::param('id/d');

        // 参数验证
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 查询审批记录
        $record = Db::name('approval_record')
            ->where('id', $id)
            ->where('user_id', $user['id']) // 只能撤销自己提交的申请
            ->where('status', 1) // 只能撤销待审批的记录
            ->find();
            
        if (!$record) {
            return json(['code' => 400, 'msg' => '审批记录不存在或已处理，无法撤销']);
        }

        // 更新审批记录
        try {
            $result = Db::name('approval_record')
                ->where('id', $id)
                ->update([
                    'status' => 4, // 已撤销
                ]);

            if ($result) {
                return json(['code' => 200, 'msg' => '撤销成功', 'data' => null]);
            } else {
                return json(['code' => 500, 'msg' => '撤销失败', 'data' => null]);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取审批详情
     */
    public function detail()
    {
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取请求参数
        $id = Request::param('id/d');
        
        // 参数验证
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 查询审批记录
        $record = Db::name('approval_record')
            ->alias('r')
            ->join('approval_flow f', 'r.flow_id = f.id')
            ->join('user u1', 'r.user_id = u1.id')
            ->join('user u2', 'r.approver_id = u2.id')
            ->where('r.id', $id)
            ->where(function($query) use ($user) {
                // 只能查看自己提交的或者自己审批的记录
                $query->where('r.user_id', $user['id'])
                      ->whereOr('r.approver_id', $user['id']);
            })
            ->field([
                'r.id',
                'r.flow_id',
                'f.title as flow_title',
                'r.form_data',
                'r.status',
                'u1.realname as applicant_name',
                'u2.realname as approver_name',
                'r.approve_time',
                'r.approve_remark',
                'r.create_time',
                'r.cancel_time'
            ])
            ->find();
            
        if (!$record) {
            return json(['code' => 404, 'msg' => '审批记录不存在']);
        }

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $record
        ]);
    }
    
    /**
     * 处理请假审批通过后的同步逻辑
     * @param array $approvalRecord 审批记录
     */
    private function handleLeaveApproval($approvalRecord)
    {
        try {
            $leaveService = new LeaveApprovalService();
            $leaveService->handleApprovalPassed($approvalRecord);
        } catch (\Exception $e) {
            // 记录错误日志，但不影响审批结果
            trace('请假记录同步失败: ' . $e->getMessage(), 'error');
        }
    }
} 